import cssMethods from "./cssTransition";
import { API } from "./network/api"
import { httpRequest, showContent } from "./network/network"

// get general dict
export const getGeneralDictByType = async type => {
  const res = await httpRequest(API.generalDict, { type });
  return res.data;
}
// preview image
export const previewImageUtils = (urls, current = "") => {
  current = current ? current : urls[0];
  wx.previewImage({
    urls: urls,
    current,
    fail: () => {
      showContent("预览图片失败");
    }
  })
}

// upload image
export const uploadImageUtils = url => {
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  return new Promise((resolve, reject) => {
    if (!url) {
      resolve();
      return;
    }
    // 解决网络图片回显后的问题
    if (url.indexOf("https") > -1) {
      resolve(url);
      return;
    }
    wx.showLoading({
      title: "图片上传中...",
    })
    const domain = wx.getStorageSync("domain");
    wx.uploadFile({
      header: {
        platformType: "MINIAPP",
        Authorization: wx.getStorageSync("token")
      },
      url: `${domain}${API.tencentUpload}`,
      filePath: url,
      name: "file",
      timeout: 30 * 1000,
      success: (res) => {
        const result = JSON.parse(res.data);
        // err code
        if (result.code > 0) {
          reject(result);
        } else {
          // success code
          resolve(result.data.filePath);
        }

      },
      fail: err => {
        showContent(err);
        reject(err);
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  })

}

// time format
export const dateToCustomFormatUtils = dateString => {
  // 将字符串转换为Date对象
  const date = new Date(dateString);

  // 获取年、月、日、小时、分钟、秒
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');

  // 组合成新的格式
  const formattedDate = `${year}.${month}.${day} ${hours}:${minutes}:${seconds}`;

  return {
    format: `${year}.${month}.${day} ${hours}:${minutes}`,
    formatMonth: `${month}.${day} ${hours}:${minutes}`,
  };
}

// distance format
export const distanceFormatUtils = distance => {
  // 定义千米和米的阈值
  const threshold = 1000;
  let formattedDistance;

  // 如果距离大于或等于1000米，则使用千米作为单位
  if (distance >= threshold) {
    formattedDistance = `${(distance / threshold).toFixed(2)} km`;
  } else {
    // 否则，使用米作为单位
    formattedDistance = `${distance} m`;
  }

  return formattedDistance;
}

/**
 *  ride time 
 * @param {*} distance 
 * @param {*} speed  default value 20/h
 */
export const calculateRideTimeUtils = (distance, speed = 20) => {
  return `${(distance / speed).toFixed(2)} h`;
}

// get location
// export const getLocationUtils = function (_this) {
//   var mapController = arguments[1];
//   wx.showLoading({
//     title: "定位中...",
//   })
//   return new Promise((resolve, reject) => {
//     wx.getLocation({
//       isHighAccuracy: true,
//       highAccuracyExpireTime: 3000,
//       success: res => {
//         let lng = res.longitude - (res.accuracy / 100000);
//         let lat = res.latitude - (res.accuracy / 10000);
//         // let lng = res.longitude;
//         // let lat = res.latitude;
//         mapController.setLocation(lng, lat);
//         _this.setData({
//           "params.lng": lng,
//           "params.lat": lat,
//         })
//         resolve(res);
//       },
//       fail: err => {
//         showContent(err);
//         reject(err);
//       },
//       complete: () => {
//         wx.hideLoading();
//       }
//     })
//   })
// }
/**
 * 解压路线数据
 * @param {*} list 
 */
export const unzipPolyLineUtils = (list = []) => {
  if (!list.length) return;
  for (var i = 2; i < list.length; i++) {
    list[i] = list[i - 2] + list[i] / 1000000;
  }
  let pointList = [];
  for (var j = 0; j < list.length; j++) {
    pointList.push({
      latitude: parseFloat(list[j]),
      longitude: parseFloat(list[j + 1])
    })
    j++;
  }
  return pointList;
}

/**
 * 进场 和 出场动画
 * @param {*} that 当前对象
 * @param {*} params 当前过渡的参数 variable:变量，默认为animation     distance:距离       time:300 时间   opacity:1 透明度
 * @param {*} methods 当前过渡的类型函数名称 默认为slideupshow
 */
export const showAnimationUtils = (that, params = {
  distance: 0,
  time: 300,
  opacity: 1
}, variable = 'animation', methods = 'slideupshow') => {
  let animationTime = 0;
  for (let key in that.data[variable]) {
    setTimeout(() => {
      that.setData({
        [`${[variable]}.${[key]}`]: cssMethods[methods](that, key, params.distance, params.opacity, true)
      })
    }, animationTime);
    animationTime += params.time;
  }
}

export const hightLightTextUtils = (text, key) => {
  const regex = new RegExp(key, "gi");
  return text.replace(regex, match => `<span class="light_text">${match}</span>`);
}

export const checkUserAuthUtils = (userId, callback, params) => {
  let status = wx.getStorageSync("userId") === userId;
  if (!status) {
    callback(params);
  }
  return wx.getStorageSync("userId") === userId;
}

export const toCamelCaseUtils = str => {
  // 将字符串转换为小写，并将下划线后的字母变为大写
  return str.toLowerCase().replace(/(_[a-z])/g, function (match) {
    // 返回匹配到的下划线后的字母大写形式
    return match.substr(1).toUpperCase();
  });
}

export const calculateDaysDifferenceUtils = targetDate => {
  const dateFormat = {};
  // 获取当前时间
  const now = new Date();
  // 将目标日期字符串转换为Date对象
  const target = new Date(targetDate);

  // 计算时间差（毫秒）
  const diff = target - now;

  // 计算天数差
  const daysDiff = Math.ceil(diff / (1000 * 60 * 60 * 24));

  // 如果目标日期是今天的日期
  if (daysDiff === 0) {
    return {
      days: 0,
      title: `今天`,
      format: "今天到啦"
    };
  }
  // 如果目标日期是未来的日期
  else if (daysDiff > 0) {
    return {
      days: daysDiff,
      title: "还有",
      format: `还有${daysDiff}天`
    };
  }
  // 如果目标日期是过去的日期
  else {
    return {
      days: -daysDiff,
      title: "已过",
      format: `已过${-daysDiff}天`
    };
  }
}